import express from 'express';
import { query, param, validationResult } from 'express-validator';
import { Expert } from '../../models/index.js';
import { optionalAuth } from '../../middleware/auth.js';
import { catchAsync, BusinessError, NotFoundError } from '../../middleware/errorHandler.js';
import { success } from '../../utils/response.js';
import { processExpertImageUrls } from '../../utils/imageUrl.js';

const router = express.Router();

// 获取启用的专家列表（小程序公开接口）
router.get('/enabled',
  optionalAuth,
  [
    query('domain_id').optional().isInt({ min: 1 }).withMessage('领域ID必须是正整数')
  ],
  catchAsync(async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      throw new BusinessError('参数验证失败', errors.array());
    }

    const { domain_id } = req.query;

    let experts;
    if (domain_id) {
      experts = await Expert.getEnabledByDomain(domain_id);
    } else {
      experts = await Expert.findAll({
        where: { is_enabled: true },
        include: [{
          association: 'domain',
          attributes: ['id', 'name'],
          where: { is_enabled: true }
        }],
        order: [['sort_order', 'ASC'], ['created_at', 'ASC']]
      });
    }

    // 处理专家列表中的图片URL
    const processedExperts = await Promise.all(
      experts.map(expert => processExpertImageUrls(expert.toJSON()))
    );

    res.json(success(processedExperts, '获取启用专家列表成功'));
  })
);

// 获取专家详情
router.get('/:id',
  optionalAuth,
  [
    param('id').isInt({ min: 1 }).withMessage('专家ID必须是正整数')
  ],
  catchAsync(async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      throw new BusinessError('参数验证失败', errors.array());
    }

    const { id } = req.params;
    
    const expert = await Expert.findByIdWithDomain(id);
    if (!expert || !expert.is_enabled) {
      throw new NotFoundError('专家不存在');
    }

    // 只返回启用领域的专家
    if (!expert.domain.is_enabled) {
      throw new NotFoundError('专家不存在');
    }

    // 处理专家详情中的图片URL
    const processedExpert = await processExpertImageUrls(expert.toJSON());

    res.json(success(processedExpert, '获取专家详情成功'));
  })
);

export default router;
